package com.itheima.interceptors;

import com.alibaba.fastjson.JSON;
import com.itheima.common.utils.RedisUtils;
import com.itheima.pojo.Member;
import com.itheima.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @version V1.0
 * @author: yongjichu
 * @date: 2020/2/6 20:16
 * @description:
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired(required = false)
  private RedisUtils redisUtils;
    /**
     * preHandle是在controller了执行前执行的，正好可以在这里进行对token的判断
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //获取存在浏览器头信息中的token
        String token = request.getHeader("token");
        if(null==token){
            //1.告诉客户端要跳转的页面
            noLogin(response);
            return false;
        }
        String memberJson = redisUtils.get(token);
        Member member = JSON.parseObject(memberJson, Member.class);
        if(member==null){
            //1.告诉客户端要登陆的页面
            noLogin(response);
        }
        return true;
    }
    private void noLogin(HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");//告诉客户端我现在写的是一段json
        PrintWriter writer = response.getWriter();
        //在Result实体类中添加一个needLogin方法
        writer.print(JSON.toJSONString(Result.needLogin()));
        writer.close();
    }
}
